package personal.zq.practice.common.utils;

import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import lombok.extern.slf4j.Slf4j;

/**
 * 登录用户工具类
 *
 * @version 1.0
 * @date 2022/9/21
 */
@Slf4j
public class AppUserInfoWrapUtil {

    /**
     * 工具类不能被实例化
     */
    private AppUserInfoWrapUtil() {
    }

    /**
     * 获取操作人ID
     *
     * @return
     */
    public static Long getOperatorId() {
        AppUserInfo appUserInfo = AppUtil.getAppUserInfo();
        return appUserInfo == null ? 0 : (appUserInfo.getOperatorId() == null ? 0 : appUserInfo.getOperatorId());
    }

    /**
     * 临时使用operatorId处理特殊请求
     *
     * @param tmpUserId
     * @param task
     * @param <V>
     * @return
     */
    public static <V> V futureUserTempUser(Long tmpUserId, FutureTask<V> task) {
        Objects.requireNonNull(tmpUserId);
        Objects.requireNonNull(task);
        Long curUID = getOperatorId();
        // 防止需要不登陆支持
        if (AppUtil.getAppUserInfo() == null) {
            AppUtil.setAppUserInfo(new AppUserInfo());
        }
        try {
            AppUtil.getAppUserInfo().setOperatorId(tmpUserId);
            task.run();
            // 设置为请求用户
            return task.get();
        } catch (InterruptedException | ExecutionException e) {
            //            log.info(" operatorId 临时替换异常", e);
            e.printStackTrace();
        } finally {
            // 还原userId
            AppUtil.getAppUserInfo().setOperatorId(curUID);
        }
        return null;
    }
}